package cn.comon;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;

/*
 * CSV文件导出工具类
 */
public class CSVUtil {

    /**
     * CSV文件生成方法
     */
    public static File createCSVFile(Object[] head, List<Object[]> lsNew,
                                     String outPutPath, String filename) {

        File csvFile = null;
        BufferedWriter csvWriter = null;
        try {
            csvFile = new File(outPutPath + File.separator + filename + ".csv");
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            // GB2312使正确读取分隔符","
            csvWriter = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(csvFile.toPath()), "GB2312"), 1024);
            // 写入文件头部
            writeRow(head, csvWriter);

            // 写入文件内容
            if (lsNew != null && !lsNew.isEmpty()){
                for (Object[] row : lsNew) {
                    writeRow(row, csvWriter);
                }
                csvWriter.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                Objects.requireNonNull(csvWriter).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    private static void writeRow(Object[] row, BufferedWriter csvWriter) throws IOException {
        // 写入文件头部
        for (Object data : row) {
            String rowStr = "\"" + data + "\",";
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }

}
